package cc.messcat.web.fupin;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.validator.internal.util.privilegedactions.GetAnnotationParameter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.entity.fupin.Family;
import cc.messcat.entity.fupin.FamilyHistory;
import cc.messcat.entity.fupin.PoorFamily;
import cc.messcat.entity.fupin.PoorFamilyHistory;
import cc.messcat.entity.fupin.RidPoor;
import cc.messcat.entity.fupin.VisitRecd;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.system.ApplicationProperties;
import cc.messcat.entity.system.McUser;
import cc.messcat.log.OperationLog;
import cc.messcat.service.fupin.FamilyService;
import cc.messcat.service.fupin.PoorFamilyService;
import cc.messcat.service.fupin.RidPoorService;
import cc.messcat.service.fupin.VisitRecdService;
import cc.messcat.service.helppeson.HelppesonService;
import cc.messcat.service.system.UserService;

@Controller
@RequestMapping("/ridPo")
public class RidPoorController {
	
	@Autowired
	private RidPoorService ridPoorService;
	
	@Autowired
	private VisitRecdService visitRecdService;
	
	@Autowired
	private PoorFamilyService poorFamilyService;
	
	@Autowired
	private FamilyService familyService;
	
	@Autowired
	private HelppesonService helppesonService;
	
	@Autowired
	public UserService userService;
	
	@RequestMapping("/addRidPoor")
	@ResponseBody
	public Object addRidPoor(@Valid RidPoor ridPoor,Long pid,HttpSession session) throws Exception{
		McUser user = userService
			.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		PoorFamily poorFamily = this.poorFamilyService.get(pid);
		poorFamily.setPoverty(ridPoor.getChanges());
		String annual = ApplicationProperties.getAnnual();
		ridPoor.setReTime(new Date());
		ridPoor.setAnnual(annual);
		
		if(ridPoor.getChanges().equals("已脱贫")){
			ridPoor.setChanges("0");
		}else {
			ridPoor.setChanges("1");
		}
		ridPoor.setOriginPoorFamily(poorFamily);
		PoorFamilyHistory poorFamilyHistory = generatePoorFamilyHistory(poorFamily);
		poorFamilyHistory.setFamilyHistories(null);
		ridPoor.setPoorFamilyHistory(poorFamilyHistory);
		poorFamilyService.addPoorFamilyHistofy(poorFamilyHistory);
		
		ridPoorService.addObject(ridPoor);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS);
	}
	
    /**
     * 贫困户变更查询
     */	
	@OperationLog(desc="贫困户变更查询",module="帐表查询")
	@RequestMapping("/queryRidPoor")
	@ResponseBody
	public Object queryRidPoor(@Valid RidPoor ridPoor,String name,String idNumber,Integer pageNo, Integer pageSize,HttpServletRequest req,HttpServletRequest request,String country,String village){
		 if (pageNo == null || pageNo < 1) {
	            pageNo = 1;
	        }
	        if (pageSize == null || pageSize < 1) {
	            pageSize = 10;
	        }
	        McUser user = (McUser)req.getSession().getAttribute("user");
	        String pid = request.getParameter("pid");
	        ridPoor.setAnnual(request.getParameter("years"));
	       Pager pager = this.ridPoorService.getPagertwo(ridPoor,name,idNumber,pageNo, pageSize,user,pid,country,village);
	       
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS,pager);
	}
	
	
	 /**
     * 贫困户变更根据id查询
     */	
	@RequestMapping("/queryRidPoorid")
	@ResponseBody
	public Object queryRidPoorid(Long id){
		 List<RidPoor> ridPoors = this.ridPoorService.RidPoor(id);
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS,ridPoors);
	}
	
	/**
	 * 贫困户变更查询导出
	 */
	@OperationLog(desc="贫困户变更查询导出",module="帐表查询")
	@RequestMapping("/exportqueryRidPoor")
	@ResponseBody
	public Object exportqueryRidPoor(@Valid RidPoor ridPoor,String name,String idNumber,HttpSession session,HttpServletRequest request,HttpServletResponse response,String country,String village) {
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		try {
			 String pid = request.getParameter("pid");
			 ridPoor.setAnnual(request.getParameter("years"));
			HSSFWorkbook wb = ridPoorService.exportVisitRecd(ridPoor,name,idNumber,user,pid,country,village);
			
			response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("贫困户变更","UTF-8")+".xls");
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
			wb.write(bufferedOutputStream);
			bufferedOutputStream.close();
			
			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_EXPORT_SUCCESS);
		} catch (IOException e) {
			e.printStackTrace();
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_EXPORT_FAIL);
		}
	}

	/**
	 * 生成家庭成员变更记录
	 * @param family
	 * @return
	 */
	private FamilyHistory generateFamilyHistory(Family family) {
		FamilyHistory familyHistory = new FamilyHistory();
		BeanUtils.copyProperties(family, familyHistory);
		familyHistory.setId(null);
		familyHistory.setOriginId(family.getId());
		return familyHistory;
	}
	/**
	 * 生成贫困户变更记录
	 * @param family
	 * @return
	 */
	private PoorFamilyHistory generatePoorFamilyHistory(PoorFamily poorFamily) {
		PoorFamilyHistory poorFamilyHistory = new PoorFamilyHistory();
		BeanUtils.copyProperties(poorFamily, poorFamilyHistory);
		poorFamilyHistory.setId(null);
		poorFamilyHistory.setOriginId(poorFamily.getId());
		return poorFamilyHistory;
	}
	
}
